package com.mosai.alignpro;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;

import com.mosai.alignpro.api.API;
import com.mosai.alignpro.event.LoadingDialogEvent;
import com.mosai.alignpro.util.LanguageUtils;
import com.mosai.alignpro.util.LogUtils;
import com.mosai.alignpro.util.ToastUtils;
import com.mosai.alignpro.view.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by Rays on 2020/3/25.
 */
public class BaseActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    private static final String TAG = BaseActivity.class.getSimpleName();

    private LoadingDialog loadingDialog;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private final EventBus eventBus = new EventBus();

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LanguageUtils.attachBaseContext(newBase));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i(TAG, "onCreate: " + this);
        eventBus.register(this);
        ToastUtils.init(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoadingDialogEvent(LoadingDialogEvent event) {
        if (event.isShow) {
            showLoadingDialog();
        } else {
            dismissLoadingDialog();
        }
    }

    public void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    protected void addDisposable(Disposable disposable) {
        compositeDisposable.add(disposable);
    }

    public void postEvent(Object event) {
        if (!isFinishing()) {
            LogUtils.i(TAG, "postEvent event: " + event);
            eventBus.post(event);
        }
    }

    public void onError(Throwable tr) throws Exception {
        LogUtils.i(TAG, "onError");
        postEvent(LoadingDialogEvent.DISMISS);
        API.ON_ERROR.accept(tr);
    }

    @Override
    protected void onDestroy() {
        LogUtils.i(TAG, "onDestroy: " + this);
        eventBus.unregister(this);
        dismissLoadingDialog();
        compositeDisposable.dispose();
        super.onDestroy();
    }
}
